//
//  AppDelegate.m
//  Router
//
//  Created by teki on 15/10/13.
//  Copyright © 2015年 dc. All rights reserved.
//

#import "AppDelegate.h"
#import "DiscoverHelper.h"
#import "BindWIFIListViewController.h"
#import "AFNetworkReachabilityManager.h"

#import <Fabric/Fabric.h>
#import <Crashlytics/Crashlytics.h>

@interface AppDelegate ()
@property (nonatomic, strong) DiscoverHelper *discoverHelper;
@property (nonatomic, strong) NSTimer *timer;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];

    
    // Override point for customization after application launch.
    [Fabric with:@[[Crashlytics class]]];
    
//    [[Crashlytics sharedInstance] crash];
    
    NSString *password = [UserSingleton shareInstance].password;
    if (password)
    {
        LoginResponseModel *model = [UserSingleton shareInstance].userModel;
        if ([model.bindDevice count]== 0) {
            BindWIFIListViewController *buynowVC = [[BindWIFIListViewController alloc] init];
            BaseNavigationViewController *baseNav = [[BaseNavigationViewController alloc] initWithRootViewController:buynowVC];
            self.window.rootViewController = baseNav;
        }
        else{
            UIStoryboard *main = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            UIViewController *mainVC = [main instantiateViewControllerWithIdentifier:@"MainVC"];
            self.window.rootViewController = mainVC;
        }
    }
    

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    [self stopTimer];
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    [[AFNetworkReachabilityManager sharedManager] stopMonitoring];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    [self startTimer];
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (status == AFNetworkReachabilityStatusReachableViaWiFi)
        {
            NSLog(@"WIFI");
            [self startTimer];
        }
        else if (status == AFNetworkReachabilityStatusReachableViaWWAN){
            NSLog(@"蜂窝网络");
            [self stopTimer];
        }
        else if (status == AFNetworkReachabilityStatusUnknown)
        {
            NSLog(@"不知道什么网络");
        }else{
            NSLog(@"没网");
        }
    }];
    
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}



- (void)startTimer
{
    [self stopTimer];
    
    self.timer = [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(findNewWIFI) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSDefaultRunLoopMode];
}



- (void)findNewWIFI
{
    __weak __typeof(self)weakSelf = self;
    [self.discoverHelper discoverWIFISuccess:^(BOOL succ, id responseObject, NSString *msg) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"responseObject:%@",responseObject);
        if (responseObject)
        {
            NSString *info = responseObject[@"info"];
            if ([info isEqualToString:@"InterNetNotConnected"])
            {
                NSString *type = responseObject[@"type"];
                if ([type isEqualToString:@"dhcp"])
                {
//                    strongSelf.netType = NetTypeDHCP;
                }
                else if ([type isEqualToString:@"static"]){
//                    strongSelf.netType = NetTypePPPOE;
                }
                else if ([type isEqualToString:@"ip"]){
//                    strongSelf.netType = NetTypeIP;
                }
                else if ([type isEqualToString:@"linkoff"])
                {
//                    [strongSelf promptMessage:@"网线没有插入WAN口!"];
                }
            }
            else if ([info isEqualToString:@"InterNetConnected"])
            {
                NSString *deviceID = responseObject[@"deviceID"];
                [strongSelf checkDeviceInBindWithDeviceID:deviceID];
            }
        }
    } failure:^(NSError *error) {
        /// 可以判断这个用的不是小叶WIFI
    }];
}



- (void)checkDeviceInBindWithDeviceID:(NSString *)deviceID
{
    if (deviceID) {
        [self.discoverHelper getWIFIBindDeviceWithDeviceID:deviceID success:^(BOOL succ, id responseObject, NSString *msg) {
            if (responseObject) {
                BOOL bindOrNot = [responseObject[@"isBind"] boolValue];
                if (!bindOrNot)
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:TK_FindNewWIFINotification object:@(YES)];
                }
                else
                {
                    [[NSNotificationCenter defaultCenter] postNotificationName:TK_FindNewWIFINotification object:@(NO)];
                }
            }
        } failure:^(NSError *error) {

        }];
    }
    
}


- (void)stopTimer
{
    if (self.timer)
    {
        
        [self.timer invalidate];
        self.timer = nil;
    }
}



- (DiscoverHelper *)discoverHelper
{
    if (!_discoverHelper)
    {
        _discoverHelper = [[DiscoverHelper alloc] init];
    }
    return _discoverHelper;
}
@end
